<?php
class CRbacManager extends CDbAuthManager{
	/**
	 * This function is an overriden method
	 * Returns the authorization items of the specific type and user.
	 * @param integer $type the item type (0: operation, 1: task, 2: role). Defaults to null,
	 * meaning returning all items regardless of their type.
	 * @param mixed $userId the user ID. Defaults to null, meaning returning all items even if
	 * they are not assigned to a user.
	 * @return array the authorization items of the specific type.
	 */
	public function getAuthItems($type=null,$userId=null)
	{
		if($type===null && $userId===null)
		{
			$sql="SELECT * FROM {$this->itemTable}";
			$command=$this->db->createCommand($sql);
		}
		else if($userId===null)
		{
			$sql="SELECT * FROM {$this->itemTable} WHERE type=:type";
			$command=$this->db->createCommand($sql);
			$command->bindValue(':type',$type);
		}
		else if($type===null)
		{
			$sql="SELECT name,type,description,t1.bizrule,t1.data
				FROM {$this->itemTable} t1, {$this->assignmentTable} t2
				WHERE name=itemname AND userid=:userid";
			$command=$this->db->createCommand($sql);
			$command->bindValue(':userid',$userId);
		}
		else
		{
			$sql="SELECT name,type,description,t1.bizrule,t1.data
				FROM {$this->itemTable} t1, {$this->assignmentTable} t2
				WHERE name=itemname AND type=:type AND userid=:userid";
			$command=$this->db->createCommand($sql);
			$command->bindValue(':type',$type);
			$command->bindValue(':userid',$userId);
		}
		$items=array();
		foreach($command->queryAll() as $row)
		{
			if(($data=@unserialize($row['data']))===false)
				$data=null;
			$items[$row['name']]=new CRbacItem($this,$row['name'],$row['type'],$row['description'],$row['bizrule'],$data,$this->getParent($row['name']));
			$items[$row['name']]->setParentChildId($this->getParentChildId($items[$row['name']]->name,$items[$row['name']]->_parent));
		}
		return $items;
	}
	/**
	 * return the parent item of a specific item
	 */
	public function getParent($item){
		$sql="SELECT `parent` FROM {$this->itemChildTable} WHERE `child`=:child";
		$command=$this->db->createCommand($sql);
		$command->bindValue(':child',$item);
		return $command->queryScalar();
	}
	/**
	 * return parent child id of a specific item
	 */
	public function getParentChildId($child, $parent){
		$sql="SELECT `id` FROM {$this->itemChildTable} WHERE `child`=:child AND `parent`=:parent";
		$command=$this->db->createCommand($sql);
		$command->bindValue(':child',$child);
		$command->bindValue(':parent',$parent);
		return $command->queryScalar();
	}
}